package handler

import (
	"context"
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"gitee.com/DonHz/cloud-file-storage/config"
	"gitee.com/DonHz/cloud-file-storage/db"
	"gitee.com/DonHz/cloud-file-storage/service/account/proto"
	"gitee.com/DonHz/cloud-file-storage/util"
	"time"
)

type UserService struct {
}

func (s *UserService) SignUp(c context.Context, req *proto.ReqSignUp, resp *proto.RespSignup) error {
	username := req.Username
	password := req.Password
	phone := req.Phone
	// 校验参数
	if len(phone) != 11 {
		resp.Code = 400
		resp.Msg = "手机号长度错误"
		return nil
	}
	if len(password) < 6 {
		resp.Code = 400
		resp.Msg = "密码长度错误"
		return nil
	}
	if len(username) < 3 || len(username) > 16 {
		resp.Code = 400
		resp.Msg = "用户名长度错误"
		return nil
	}
	encPassword := util.Sha1([]byte(password + config.PasswordSalt))
	// 保存用户信息
	err := db.SignUp(phone, encPassword, username)
	if err != nil {
		resp.Code = 500
		resp.Msg = "注册失败"
		return nil
	}
	resp.Code = 200
	resp.Msg = "注册成功"
	return nil
}

func (s *UserService) SignIn(ctx context.Context, req *proto.ReqSignIn, resp *proto.RespSignin) error {
	username := req.Username
	password := req.Password

	// 校验参数
	phone := username
	user, err := db.SignIn(phone, password)
	if err != nil {
		resp.Code = 500
		resp.Msg = "手机号或密码错误"
		resp.Token = ""
		return nil
	}
	//生成token
	timestamp := fmt.Sprintf("%d", time.Now().Unix())
	tokenPrefix := md5.Sum([]byte(phone + timestamp + "token_salt"))
	token := hex.EncodeToString(tokenPrefix[:]) + timestamp[:8]

	_, err = db.UpdateToken(user.Phone, token)
	//body := struct {
	//	Id       int64  `json:"id"`
	//	UserName string `json:"Username"`
	//	Token    string `json:"Token"`
	//}{
	//	Id:       res.Id,
	//	UserName: res.Phone,
	//	Token:    token,
	//}
	if err != nil {
		resp.Code = 500
		resp.Msg = "更新token失败"
		resp.Token = ""
		return nil
	}
	resp.Code = 200
	resp.Msg = "登录成功"
	resp.Token = token
	return nil
}

func (s *UserService) GetUserInfo(ctx context.Context, req *proto.ReqUserInfo, resp *proto.RespUserInfo) error {
	//校验token
	fmt.Println(req)
	username := req.Username
	// 查询用户信息
	user, err := db.GetUserInfo(username)
	if err != nil {
		resp.Code = 500
		resp.Msg = "系统错误"
		resp.User = nil
		return nil
	}
	resp.Code = 200
	resp.Msg = "查询成功"
	resp.User = &proto.User{
		Phone:      user.Phone,
		Username:   user.UserName,
		CreateTime: time.Unix(user.CreateAt, 0).Format("2006-01-02 15:04:05"),
	}
	return nil
}
